#include "widget.h"
#include "connection.h"
#include "Utils/C_SingleApplication.h"

#include <QDebug>
#include <QMessageLogContext>
#include <QFile>
#include <QTextStream>
#include <QDateTime>
#include <QMutex>

void outputMessage(
        QtMsgType type,
        const QMessageLogContext &context,
        const QString &msg
        );

int main(int argc, char *argv[])
{
    C_SingleApplication a(argc, argv);

    if ( ! a.IsRunning())
    {
        //注册MessageHandler
        qInstallMessageHandler(outputMessage);


        //设置当前路径为可执行程序路径
        if( ! QDir::setCurrent(QCoreApplication::applicationDirPath()))
        {
            qDebug() << QString("Set current path error!");
            qDebug() << QCoreApplication::applicationDirPath();
            return false;
        }

        //连接数据库
        if ( ! createConnection())
        {
            qDebug() << "connection error!";
            return 1;
        }

        //显示主界面
        Widget w;
        a.SetWidget(&w);
        w.hide();

        QObject::connect(&a, SIGNAL(newLocalConnection()),
                         &w, SLOT(onChangeWallPaper()));

        return a.exec();
    }

    return 0;
}

//定义日志输出格式
void outputMessage(
        QtMsgType type,
        const QMessageLogContext &context,
        const QString &msg
        )
{
    static QMutex mutex;
    mutex.lock();

    QString text;
    switch(type)
    {
    case QtDebugMsg:
        text = QString("Debug:");
        break;

    case QtWarningMsg:
        text = QString("Warning:");
        break;

    case QtCriticalMsg:
        text = QString("Critical:");
        break;

    case QtFatalMsg:
        text = QString("Fatal:");
        break;

    case QtInfoMsg:
        text = QString("Info:");
        break;

    default:
        text = QString("Error:");
    }
    //enum QtMsgType { QtDebugMsg, QtWarningMsg, QtCriticalMsg,
    //      QtFatalMsg, QtInfoMsg, QtSystemMsg = QtCriticalMsg };

    QString context_info = QString("File:(%1) Line:(%2)")
            .arg(QString(context.file))
            .arg(context.line);
    QString current_date_time = QDateTime::currentDateTime()
            .toString("yyyy-MM-dd hh:mm:ss ddd");
    QString current_date = QString("(%1)")
            .arg(current_date_time);
    QString message = QString("%1 %2 %3 %4")
            .arg(text)
            .arg(context_info)
            .arg(msg)
            .arg(current_date);

    QFile file("log.txt");
    file.open(QIODevice::WriteOnly | QIODevice::Append);
    QTextStream text_stream(&file);
    text_stream << message << "\r\n";
    file.flush();
    file.close();

    mutex.unlock();
}
